package com.bytecub.udp.service.parser;

import com.bytecub.common.domain.gateway.mq.ServiceInvokeMessageBo;
import com.bytecub.common.domain.message.DeviceDownMessage;
import com.bytecub.mdm.cache.IDownMessageCache;
import com.bytecub.protocol.base.IBaseProtocol;
import com.bytecub.protocol.domain.bo.DeviceProductBo;
import com.bytecub.protocol.service.IProtocolUtilService;
import com.bytecub.storage.IMessageReplyService;
import com.bytecub.storage.entity.MessageReplyEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 *  * ByteCub.cn.
 *  * Copyright (c) 2020-2021 All Rights Reserved.
 *  * 
 *  * @author bytecub@163.com  songbin
 *  * @Date 2021/4/6  Exp $$
 *  
 */
@Slf4j
@Service
public class DownMessageParser {
    @Autowired
    IDownMessageCache downMessageCache;
    @Autowired
    IProtocolUtilService protocolUtilService;
    @Autowired
    IMessageReplyService messageReplyService;

    public byte[] encode(String deviceCode){
        List<DeviceDownMessage> downMessages = this.serviceData(deviceCode);
        if(CollectionUtils.isEmpty(downMessages)){
            return "".getBytes();
        }
        DeviceProductBo deviceProductBo = protocolUtilService.queryInstanceByDeviceCode(deviceCode);
        byte[] ret = deviceProductBo.getBaseProtocol().encodeBatch( deviceCode, downMessages);
        this.saveRet(downMessages);
        return null == ret ? "".getBytes() : ret;
    }
    private List<DeviceDownMessage> serviceData(String deviceCode){
        List<DeviceDownMessage> list = downMessageCache.downMessageReader(deviceCode);
        return list;
    }
    /**对于UDP协议 只要下发了 就认为成功了*/
    public void saveRet(List<DeviceDownMessage> downMessages){
        for(DeviceDownMessage deviceMessage : downMessages){
            try{
                MessageReplyEntity messageReplyEntity = new MessageReplyEntity();
                messageReplyEntity.setMessageId(deviceMessage.getMessageId());
                messageReplyEntity.setBody("已下发[UDP只管下发]");
                messageReplyEntity.setDeviceCode(deviceMessage.getDeviceCode());
                messageReplyEntity.setDevTimestamp(new Date());
                messageReplyEntity.setProductCode(deviceMessage.getProductCode());
                messageReplyEntity.setTimestamp(new Date());
                messageReplyEntity.setStatus(200);
                messageReplyService.create(messageReplyEntity);
            }catch (Exception e){
                log.warn("", e);
                continue;
            }

        }

    }
}
